/**
 * File.java
 * uAPI Public License
 * @change delete is keyword in C(++) method renamed to del
 * @change method listFiles add
 */
package uapi.io;

/**
 * Implementation from entry in the file allocation table.
 *
 * @author Bastie - Sebastian Ritter
 * @version 1.0
 */
public class File {

  /**
   * @pattern Delegate
   */
  protected java.io.File delegate;

  /**
   * Construct a new File instance
   */
  public File () { // C++ need it
    this ("/");
  }

  /**
   * Construct a new File instance with given path
   * @param path String
   */
  public File (final String path) {
    this.delegate = new java.io.File (path);
  }

  /**
   * Construct a new File instance with given delegate objekt
   * @param delegate File
   */
  File (final java.io.File delegate) {
    this.delegate = delegate;
  }

  /**
   * Check the exists of file
   * @return boolean
   */
  public boolean exist () {
    return this.delegate.exists();
  }
  /**
   * Check file type is a directory
   * @return boolean
   */
  public boolean isDirectory () {
    return this.delegate.isDirectory();
  }
  /**
   * Check file type is a file
   * @return boolean
   */
  public boolean isFile () {
    return this.delegate.isFile();
  }
  /**
   * Create a directory with not existing subdirectory that represent the
   * file
   * @return boolean
   */
  public boolean makeDirectory () {
    return this.delegate.mkdirs();
  }
  /**
   * Delete the file
   * @return boolean
   */
  public boolean del () {
    return this.delegate.delete();
  }
  /**
   * Rename the file
   * @param newName String
   * @return boolean
   */
  public boolean rename (final String newName) {
    boolean ok = false;
    synchronized (this.delegate) {
      java.io.File renamed = new java.io.File (newName);
      ok = this.delegate.renameTo (renamed);
      if (ok) {
        this.delegate = renamed;
      }
    }
    return ok;
  }

  /**
   * Return a string that represents the file
   * @return String
   */
  public String toString () {
    return this.delegate.getAbsolutePath();
  }

  /**
   * &quot;destruct&quot;
   */
  public void finalize () throws Throwable{
    this.delegate = null;
  }

  /**
   * List all files in the directory
   * @return File[]
   * @pattern NullPattern
   */
  public File [] listFiles () {
    if (this.isDirectory()) {
      final java.io.File[] sub = this.delegate.listFiles ();
      final File[] retValue = new File[sub.length];
      for (int i = 0; i < sub.length; i++) {
        retValue[i] = new File (sub[i]);
      }
      return retValue;
    }
    return new File[0]; // NullPattern
  }
}
